import { AxiosInstance, AxiosResponse } from 'axios'
import { useAuthStore } from '@/store'
import { resolveResError } from '@/utils/http/helpers.ts'
import { message as Message } from 'ant-design-vue'

export function setupInterceptors(axios: AxiosInstance) {
  function requestResolve(config: any) {
    if (config.noNeedToken) {
      return config
    }
    const { accessToken } = useAuthStore()
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`
    }
    return config
  }

  function requestReject(error: any) {
    return Promise.reject(error)
  }

  const SUCCESS_CODES = [0, 200, 201]

  function responseResolve(response: AxiosResponse<any>) {
    const { data, status, config, statusText, headers } = response
    if (headers['content-type'] === 'application/json') {
      if (SUCCESS_CODES.includes(data?.statusCode)) {
        return Promise.resolve(data)
      }

      const code = data?.statusCode ?? status

      const message = resolveResError(code, data?.message ?? statusText)

      !(config as any)?.noNeedTip && message && Message.error(message)
      return Promise.reject({ code, message, error: data ?? response })
    }
    return Promise.resolve(data ?? response)
  }

  function responseReject(error: any) {
    if (!error || !error.response) {
      const code = error?.code

      const message = resolveResError(code, error.message)
      Message.error(message).then(() => {})
      return Promise.reject({ code, message, error })
    }

    const { data, status, config } = error.response
    const code = data?.statusCode ?? status

    const message = resolveResError(code, data?.message ?? error.message)

    !config?.noNeedTip && message && Message.error(message)
    return Promise.reject({ code, message, error: error.response?.data || error.response })
  }

  axios.interceptors.request.use(requestResolve, requestReject)
  axios.interceptors.response.use(responseResolve, responseReject)
}
